package com.mongo.api;

import com.tanhua.dubbo.mongo.CommentAPI;
import com.tanhua.mongo.Comment;
import com.tanhua.vo.CommentType;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class CommentAPIImpl implements CommentAPI {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Integer save(Comment comment) {
        Comment save = mongoTemplate.save(comment);
        //获取当前评论的点赞数
        Query query = new Query(Criteria.where("publishId").is(comment.getPublishId()).and("commentType").is(comment.getCommentType()));

        return (int)mongoTemplate.count(query,Comment.class);
    }

    @Override
    public Integer delete(Comment comment) {

        Query query = new Query(Criteria.where("publishId").is(comment.getPublishId())
                                    .and("commentType").is(comment.getCommentType())
                                    .and("userId").is(comment.getUserId()));
        mongoTemplate.remove(query,Comment.class);

        Query countQuery = new Query(Criteria.where("publishId").is(comment.getPublishId()).and("commentType").is(comment.getCommentType()));

        return (int)mongoTemplate.count(countQuery,Comment.class);
    }

    @Override
    public PageResult findByPage(String movementId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                                     .and("commentType").is(CommentType.COMMENT);

        Query query = new Query(criteria)
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        //查询数据
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        //封装pageResut
        PageResult pr = new PageResult();
        pr.setPage(page);
        pr.setPagesize(pagesize);
        Query countQuery = new Query(criteria);
        long count = mongoTemplate.count(countQuery, Comment.class);
        pr.setCounts((int) count);
        long pages = count%pagesize==0?count/pagesize:(count/pagesize+1);
        pr.setPages((int)pages);
        pr.setItems(commentList);

        return pr;
    }
}
